<template>
  <div>
    <div v-show="isMain" class="equip-wrap-common">
      <px-form ref="searchFormRef" class="custom-form-ui equip-form" :model="queryParams" label-position="right" label-width="120px">
        <px-row :gutter="16">
          <px-col :span="6">
            <px-form-item label="任务单号" prop="workOrderCode">
              <px-input
                v-model="queryParams.workOrderCode"
                placeholder="请输入任务单号"
                maxlength="50"
                clearable
                @blur="queryParams.workOrderCode = $event.target.value.trim()"
                @keyup.enter="queryTable"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="工单主题" prop="workOrderName">
              <px-input v-model="queryParams.workOrderName" clearable placeholder="请输入工单主题" maxlength="50" @keyup.enter="queryTable">
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="执行人" prop="executorId">
              <px-select-v2 v-model="queryParams.executorId" filterable clearable :options="approvalList" placeholder="请选择执行人" />
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="优先级" prop="weight">
              <px-select v-model="queryParams.weight" placeholder="请选择优先级" clearable filterable>
                <px-option v-for="item in faultLevelList" :key="item.id" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="工单状态" prop="workOrderStatus">
              <px-select v-model="queryParams.workOrderStatus" placeholder="请选择工单状态" clearable filterable>
                <px-option v-for="item in statusList" :key="item.id" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="地块" prop="facCode">
              <px-select v-model="queryParams.facCode" placeholder="请选择地块" clearable filterable>
                <px-option v-for="item in facCodeList" :key="item.id" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-button type="primary" @click="queryTable">查询</px-button>
            <px-button @click="resetTable">重置</px-button>
          </px-col>
        </px-row>
      </px-form>
      <div class="equip-table-btn">
        <px-button v-has="'ERC_MAINTAIN_ADD'" type="primary" @click="handleAdd">新增</px-button>
      </div>
      <px-table :data="tableData" class="equip-table" size="small" height="calc(100vh - 352px)" border>
        <px-table-column type="index" label="序号" width="60" align="center" fixed />
        <px-table-column fixed="left" prop="workOrderCode" label="任务单号" min-width="130" show-overflow-tooltip>
          <template #default="scope">
            <span v-if="isHasPermission('ERC_MAINTAIN_DETAIL')" style="color: #3b82f6; cursor: pointer" @click="handleView(scope.row)">
              {{ scope.row.workOrderCode }}
            </span>
            <span v-else>{{ scope.row.workOrderCode }}</span>
          </template>
        </px-table-column>
        <px-table-column prop="workOrderName" label="工单主题" min-width="150" show-overflow-tooltip />
        <px-table-column prop="createName" label="报修人" min-width="120" show-overflow-tooltip />
        <px-table-column prop="weightDesc" label="优先级" min-width="80" show-overflow-tooltip>
          <template #default="scope">
            <span :style="{ color: scope.row.weightDesc === '紧急维修' ? 'red' : '' }">{{ scope.row.weightDesc }}</span>
          </template>
        </px-table-column>
        <px-table-column prop="eqpName" label="故障设备" min-width="120" show-overflow-tooltip />
        <px-table-column prop="facCodeDesc" label="所处地块" min-width="120" show-overflow-tooltip />
        <px-table-column prop="positionCodeDesc" label="设备位置" min-width="180" show-overflow-tooltip />
        <px-table-column prop="faultDesc" label="问题描述" min-width="150" show-overflow-tooltip />
        <px-table-column prop="isStop" label="是否消防中断" min-width="110" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.isStop === 1 ? "是" : "否" }}</span>
          </template>
        </px-table-column>
        <px-table-column prop="isFireIsolation" label="是否隔离" min-width="80" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.isFireIsolation === 1 ? "是" : "否" }}</span>
          </template>
        </px-table-column>
        <px-table-column prop="createTime" label="报修时间" min-width="150" show-overflow-tooltip />
        <px-table-column prop="completionTime" label="完成时间" min-width="150" show-overflow-tooltip />
        <px-table-column prop="executorInfo" label="执行人" min-width="180" show-overflow-tooltip />
        <px-table-column prop="positionCodeDesc" label="维修状态" min-width="90" show-overflow-tooltip>
          <template #default="scope">
            <!-- <div class="status" @click="handleProcess(scope.row)">
              <div class="circle" :style="{ backgroundColor: `${tagBgColorList[scope.row.workOrderStatus]}` }" />
              <p :style="{ color: `${tagBgColorList[scope.row.workOrderStatus]}` }">
                {{ scope.row.workOrderStatusDesc }}
              </p>
            </div> -->
            <px-tag
              effect="plain"
              :style="{
                color: `${tagColorList[scope.row.workOrderStatus]}`,
                border: `1px solid ${tagBorderColorList[scope.row.workOrderStatus]}`,
                backgroundColor: `${tagBgColorList[scope.row.workOrderStatus]}`,
                cursor: 'pointer'
              }"
              @click="handleProcess(scope.row)"
            >
              {{ scope.row.workOrderStatusDesc }}
            </px-tag>
          </template>
        </px-table-column>
        <px-table-column fixed="right" label="操作" min-width="160" align="center">
          <template #default="scope">
            <px-tooltip content="详情" placement="top">
              <px-button v-has="'ERC_MAINTAIN_DETAIL'" link type="primary" icon="Tickets" @click="handleView(scope.row)" />
            </px-tooltip>
            <px-tooltip v-if="[0].includes(scope.row.workOrderStatus) && scope.row.createBy === userInfo.userId" content="编辑" placement="top">
              <px-button v-has="'ERC_MAINTAIN_EDIT'" link type="primary" icon="EditPen" @click="handleEdit(scope.row)" />
            </px-tooltip>
            <px-tooltip v-if="[0, 1, 3].includes(scope.row.workOrderStatus) && scope.row.isExecutor" content="工单执行" placement="top">
              <px-button v-has="'ERC_MAINTAIN_EXECUTE'" link type="primary" icon="DocumentChecked" @click="handleExecute(scope.row)" />
            </px-tooltip>
            <px-tooltip v-if="scope.row.workOrderStatus === 0 && userInfo.userId === scope.row.createBy" content="撤销" placement="top">
              <px-button v-has="'ERC_MAINTAIN_BACK'" link type="primary" icon="Rollback" @click="handleBack(scope.row)" />
            </px-tooltip>
            <px-tooltip v-if="scope.row.workOrderStatus === 2 && scope.row.approverId === userInfo.userId" content="审核" placement="top">
              <px-button v-has="'ERC_MAINTAIN_AUDIT'" link type="primary" @click="handleAudit(scope.row)">
                <component :is="markRaw(stamp)" />
              </px-button>
            </px-tooltip>
            <px-tooltip v-if="scope.row.workOrderStatus === 2 && scope.row.isExecutor" content="转审" placement="top">
              <px-button v-has="'ERC_MAINTAIN_FORWARD'" link type="primary" @click="handleForward(scope.row)">
                <component :is="markRaw(transfer)" />
              </px-button>
            </px-tooltip>
            <!-- <px-tooltip v-if="scope.row.workOrderStatus === 4" content="打印" placement="top">
              <px-button v-has="'ERC_MAINTAIN_PRINT'" icon="Printer" type="primary" link @click="handlePrint(scope.row)" />
            </px-tooltip> -->
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        class="equip-table-pagination"
        :total="total"
        @pagination="queryTable"
      />
    </div>
    <!-- 新增页面 -->
    <AddMaintainTask
      :isMain="isMain"
      :isView="isView"
      :taskId="taskId"
      :eqpId="eqpId"
      :alarmId="alarmId"
      :title="title"
      :drawerType="drawerType"
      :shareData="{ faultLevelList }"
      @queryTable="queryTable"
      @backMainPage="backMainPage"
    />
    <MaintainDetail v-if="isView" />
    <!-- 审批弹窗 -->
    <AuditDialog :visible="isAuditShow" :taskId="taskId" @closeDialog="isAuditShow = false" @queryTable="queryTable" />
    <!-- 转审弹窗 -->
    <ForwardDialog :visible="isForwardShow" :taskId="taskId" :userInfo="userInfo" @closeDialog="isForwardShow = false" @queryTable="queryTable" />
    <!-- 处理进度弹窗 -->
    <DealProcess :visible="isProcessShow" :taskId="taskId" @closeDialog="isProcessShow = false" />
    <px-dialog v-model="isCancelShow" title="确认撤回维修任务吗？撤回后不可恢复" destroy-on-close @close="handleCancelCancel">
      <px-form ref="cancelRef" :model="cancelForm">
        <px-form-item label="备注" label-width="80px" prop="remark" :rules="[{ required: true, message: '请输入备注' }]">
          <px-input
            v-model="cancelForm.remark"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            maxlength="1000"
            placeholder="请输入撤销原因"
            clearable
          />
        </px-form-item>
      </px-form>
      <template #footer>
        <span class="dialog-footer">
          <px-button @click="handleCancelCancel">取消</px-button>
          <px-button type="primary" @click="handleCancelSubmit(cancelRef)">确认</px-button>
        </span>
      </template>
    </px-dialog>
  </div>
</template>
<script setup lang="ts">
defineOptions({
  name: "ERC_MAINTAIN_ORDER"
});
import { queryDictData } from "@/api/common";
import { backMaintainList, detailMaintainList, getModuleName, getRecordList, getStatusList, queryOrderList } from "@/api/erc/maintain";
import stamp from "@/assets/svg/operation/stamp.svg?component";
import transfer from "@/assets/svg/operation/transfer.svg?component";
import { isHasPermission } from "@/utils/auth";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import { PxMessage } from "px-ui";
import { markRaw, onMounted, reactive, ref, toRefs } from "vue";
import { useRoute, useRouter } from "vue-router";
import AddMaintainTask from "./components/AddMaintainTask.vue";
import AuditDialog from "./components/AuditDialog.vue";
import DealProcess from "./components/DealProcess.vue";
import MaintainDetail from "./components/MaintainDetail.vue";
import ForwardDialog from "./components/TransferDialog.vue";

const route = useRoute();
const router = useRouter();

const searchFormRef = ref();
const cancelRef = ref();

const state = reactive<any>({
  userInfo: "",
  isMain: true, // 主页面true 详情页面false
  isView: false, // 查看true 新增/编辑false
  isAuditShow: false, // 审核弹窗是否可见
  isForwardShow: false, // 转审弹窗是否可见
  isProcessShow: false, // 处理进度弹窗是否可见
  isCancelShow: false, // 撤销弹窗是否可见
  queryParams: {
    pageNum: 1,
    pageSize: 20
  },
  tableData: [],
  total: 0,
  drawerType: "add",
  taskId: "",
  faultLevelList: [],
  approvalList: [],
  statusList: [], // 工单状态
  detailData: {},
  eqpId: "",
  alarmId: "",
  isPrint: false,
  moduleName: "",
  orderImgList: [],
  facCodeList: [],
  title: ""
});
const {
  userInfo,
  isMain,
  isView,
  queryParams,
  tableData,
  total,
  drawerType,
  taskId,
  faultLevelList,
  approvalList,
  statusList,
  isAuditShow,
  isProcessShow,
  isForwardShow,
  isCancelShow,
  detailData,
  eqpId,
  alarmId,
  isPrint,
  moduleName,
  orderImgList,
  facCodeList,
  title
} = toRefs(state);

const tagColorList = {
  0: "#F59E0B", // 待维修
  1: "#3B82F6", // 维修中
  2: "#F59E0B", // 审核中
  3: "#EF4444", // 已驳回
  4: "#10B981", // 已完成
  5: "#909399", // 已撤销
  6: "#9254DE" // 驳回不通过
};

const tagBorderColorList = {
  0: "#FCE2B6", // 待维修
  1: "#C6E2FF", // 维修中
  2: "#FCE2B6", // 审核中
  3: "#FAC7C7", // 已驳回
  4: "#B7EAD9", // 已完成
  5: "#E9E9EB", // 已撤销
  6: "#DDC2FF" // 驳回不通过
};

const tagBgColorList = {
  0: "#FEF5E6", // 待维修
  1: "#ECF5FF", // 维修中
  2: "#FEF5E6", // 审核中
  3: "#FEECEC", // 已驳回
  4: "#E8F8F3", // 已完成
  5: "#F4F4F5", // 已撤销
  6: "#F2E7FF" // 驳回不通过
};

document.querySelector("div").addEventListener("dragstart", e => {
  e.preventDefault();
});

const getModuleNameValue = async () => {
  const data = await getModuleName();
  moduleName.value = data;
};

const handleGetApprovalList = async () => {
  approvalList.value = await getEmployeeIdAndName(["HSE", "ISEP", "ERC&FP"]);
};

// 查询列表
const queryTable = async () => {
  const data = await queryOrderList({ ...queryParams.value });
  tableData.value = data?.data || [];
  total.value = data?.total;
};
// 重置筛选条件列表
const resetTable = async () => {
  searchFormRef.value.resetFields();
  queryParams.value = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize
  };
  queryTable();
};

const getStatus = async () => {
  statusList.value = await getStatusList({});
};

// 进入页面时触发
onMounted(async () => {
  userInfo.value = JSON.parse(localStorage.getItem("userInfo"));
  const { eqpId: id, alarmId: alarm, type, maintainId, title: subTitle } = route.query;
  // 查看维修详情
  if (maintainId && type === "view") {
    router.push(`/erc/maintain/detail?id=${maintainId}`);
  }
  if (id) {
    isMain.value = false;
    drawerType.value = "add";
    isView.value = false;
    eqpId.value = id;
    alarmId.value = alarm;
    title.value = subTitle;
  }
  faultLevelList.value = await queryDictData({ typeCode: "ERC_MAINTENANCE_WEIGHT" });
  facCodeList.value = await queryDictData({ typeCode: "ERC_FACTORY_AREA" });
  getStatus();
  queryTable();
  handleGetApprovalList();
});

// 添加
const handleAdd = () => {
  drawerType.value = "add";
  isMain.value = false;
  isView.value = false;
};

// 从新增/编辑、详情返回主页面
const backMainPage = () => {
  detailData.value = {};
  taskId.value = "";
  isMain.value = true;
  drawerType.value = "";
};

/**
 * 根据图片的url转换对应的base64值
 * @param { String } imageUrl 如：http://xxxx/xxx.png
 * @returns base64取值
 * @Note 注意：可能涉及图片访问有跨域问题，让后台解决即可。
 */
const urlToBase64 = async url => {
  const res = await fetch(url, { mode: "no-cors" });
  const blob = await res.blob();
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result);
    reader.readAsDataURL(blob);
  });
};

// 获取打印数据
const getDetail = async () => {
  getModuleNameValue();
  const orderDetail = await detailMaintainList({ id: taskId.value });
  const { faultImageList = [] } = orderDetail;
  faultImageList?.forEach(async item => {
    const res = await urlToBase64(item.fileUrl);
    console.log(res);
    orderImgList.value.push(res);
  });

  const recordList = await getRecordList(taskId.value);
  detailData.value = { ...orderDetail, recordList };
};
const imageUrl = ref(null);
const handlePrint = async row => {
  taskId.value = row.id;
  isPrint.value = true;
  await getDetail();
  // const content = document.getElementById("print-template");
  // let rect = content.getBoundingClientRect();
  // html2canvas(content, { useCORS: true, allowTaint: true })
  //   .then(canvas => {
  //     imageUrl.value = canvas.toDataURL("image/png");
  //     setTimeout(() => {
  //       printJS({
  //         printable: "print-img",
  //         type: "html",
  //         style: `
  //        @media print{
  //         body,html{
  //           margin:0;
  //           padding:0;
  //           width:100%;
  //           height:${rect.height * (1080 / rect.width)}px;
  //         }
  //         #print-img {
  //           width:1080px;
  //           transform-origin:top left;
  //         }
  //         img.print-full-page{
  //           position:absolute;
  //           top:0;
  //           left:0;
  //           width:100%;
  //           height:100%;
  //           object-fit:cover;
  //           page-break-before:always;
  //           page-break-after:always;
  //           background:white;
  //         }
  //        @page {margin: 1cm;}
  //         }
  //         `, // 去掉页眉页脚
  //         scanStyles: false,
  //         // targetStyles: ['*'],
  //         header: null
  //         // documentTitle: "水课抄表"
  //       });
  //       isPrint.value = false;
  //     }, 100);
  //   })
  //   .catch(error => {
  //     isPrint.value = false;
  //     console.log("Error", error);
  //   });
};
const handleProcess = row => {
  isProcessShow.value = true;
  taskId.value = row.id;
};

// 编辑
const handleEdit = row => {
  drawerType.value = "edit";
  taskId.value = row.id;
  isMain.value = false;
  isView.value = false;
};

const handleView = row => {
  router.push(`/erc/maintain/detail?id=${row.id}`);
};
// 审核
const handleAudit = row => {
  isAuditShow.value = true;
  taskId.value = row.id;
};
const handleCloseAudit = () => {
  isAuditShow.value = false;
  queryTable();
};
// 转审
const handleForward = row => {
  isForwardShow.value = true;
  taskId.value = row.id;
};
const handleForwardClose = () => {
  isForwardShow.value = false;
  queryTable();
};
const handleExecute = (row: any) => {
  router.push(`/erc/maintain/detail?id=${row.id}&type=execute`);
};

// 撤销任务弹窗
const cancelForm = ref<Record<string, any>>({ remark: "" });
const handleCancelCancel = () => {
  isCancelShow.value = false;
  cancelForm.value = { remark: "" };
};
const handleCancelSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      await backMaintainList({ id: taskId.value, remark: cancelForm.value.remark });
      PxMessage.success("撤回成功");
      handleCancelCancel();
      queryTable();
    }
  });
};

const handleBack = row => {
  isCancelShow.value = true;
  taskId.value = row.id;
  // PxMessageBox.confirm(`确认撤回维修任务吗？撤回后不可恢复`, "提示", {
  //   confirmButtonText: "确认",
  //   cancelButtonText: "取消",
  //   type: "warning"
  // })
  //   .then(async () => {
  //     await backMaintainList({ id: row.id });
  //     PxMessage.success("撤回成功");
  //     queryTable();
  //   })
  //   .catch(() => {});
};
</script>

<style lang="scss" scoped>
@import url("@/views/erc/scss/table-list.scss");

#print-template {
  .title {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
    border-bottom: 3px solid #000;

    p:first-child,
    p:nth-child(3) {
      font-size: 14px;
      color: rgb(0 0 0 / 80%);
    }

    p:nth-child(2) {
      font-size: 36px;
      font-weight: 600;
      color: rgb(0 0 0 / 80%);
    }
  }

  .print-title {
    margin-top: 24px;
    font-size: 20px;
    font-weight: 600;
    line-height: 1.75;
    color: rgb(0 0 0 / 80%);
  }

  .print-content {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    border: 1px solid #dcdcdc;

    .print-item {
      display: flex;
      width: 50%;
      line-height: 40px;
      border-bottom: 1px solid #dcdcdc;

      &:nth-last-child(1),
      &:nth-last-child(2) {
        border: none;
      }

      &:nth-last-child(1) {
        border-top: 1px solid #dcdcdc;
      }

      .label {
        display: flex;
        align-items: center;
        justify-content: center;
        // justify-content: flex-end;
        width: 150px;
        font-size: 14px;
        font-weight: bold;
        text-align: center;
        background: #f7f7f7;
        border-right: 1px solid #dcdcdc;
      }

      .text {
        display: flex;
        flex: 1;
        align-items: center;
        padding-left: 8px;
        font-size: 14px;
        line-height: 18px;
        color: rgb(0 0 0 / 90%);
        word-break: break-all;

        .tag {
          height: 22px;
          padding: 0 8px;
          font-size: 12px;
          line-height: 22px;
          color: rgb(0 0 0 / 80%);
          text-align: center;
          border-radius: 4px;
        }
      }

      &.large {
        width: 100%;
      }
    }

    .record-list-title {
      margin: 12px auto;
      font-weight: 600;
      color: rgb(0 0 0 / 90%);
      text-align: center;
    }

    .print-table {
      box-sizing: border-box;
      margin: 12px;
    }
  }
}

#print-img {
  position: fixed;
  left: -200000px;
  width: 100%;
}
</style>
